package com.id.sigma;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;

import com.google.gson.*;
import com.google.gson.reflect.*;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;

import com.id.sigma.camel.CamelService;

import javax.servlet.http.HttpServletRequest;

//import org.slf4j.Logger;
//import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

/**
 * Handles requests for the application home page.
 */
@Controller
public class HomeController {

	/**
	 * Simply selects the home view to render by returning its name.
	 */
	public HomeController() {
	}

	@RequestMapping(value = "/", method = RequestMethod.GET)
	public ModelAndView home(Model model) {
		List<Broker> brokers = new ArrayList<Broker>();
		BufferedReader br = null;
		String data="";
		try {
			data = readURL("http://localhost:8080/sigma/core/showAllBroker");
		} catch (IOException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		
		System.out.println(data);
		JSONParser parser = new JSONParser();
		try {
			JSONArray jArray = (JSONArray) parser.parse(data);
			for (int i = 0; i < jArray.size(); i++) {
				JSONObject jObject = (JSONObject) jArray.get(i);
				Broker b = new Broker();
				b.setIdBroker(Integer.parseInt(((Long)jObject.get("idBroker")).toString()));
				b.setNamaBroker((String) jObject.get("namaBroker"));
				b.setAlamat((String) jObject.get("alamat"));
				b.setSaldoUang((Long) jObject.get("saldoUang"));
				b.setSaldoSaham((Long) jObject.get("saldoSaham"));
				brokers.add(b);
			}
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return new ModelAndView("home", "brokers", brokers);
	}

	// buat manggil form tambah broker baru
	@RequestMapping(value = "/formInsertNew", method = RequestMethod.GET)
	public ModelAndView formInput(Model model) {
		return new ModelAndView("formAddBroker");
	}

	// buat manggil form update broker
	@RequestMapping(value = "/formUpdateBroker/id/{id}", method = RequestMethod.GET)
	public ModelAndView formUpdate(@PathVariable("id") String id,
			ModelAndView model) {

		String data = null;
		try {
			data = readURL("http://localhost:8080/sigma/core/broker/get/id/"+id);
		} catch (IOException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		System.out.println(data);
		JSONParser parser = new JSONParser();
		Broker b = new Broker();
		try {
			JSONObject jObject = (JSONObject) parser.parse(data);
			b.setIdBroker(Integer.parseInt(((Long)jObject.get("idBroker")).toString()));
			b.setNamaBroker((String) jObject.get("namaBroker"));
			b.setAlamat((String) jObject.get("alamat"));
			b.setSaldoUang((Long) jObject.get("saldoUang"));
			b.setSaldoSaham((Long) jObject.get("saldoSaham"));
			// }
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		model.addObject("Broker",b);
		model.setViewName("formEditBroker");
		return model;
	}

	// action untuk form insert new broker
	@RequestMapping(value = "/insertNewBroker", method = RequestMethod.POST)
	public ModelAndView insertBrooker(@ModelAttribute("Broker") Broker broker) {
		JSONObject obj = new JSONObject();
//		obj.put("method", "input");
		obj.put("idBroker", null);
		obj.put("namaBroker", broker.getNamaBroker());
		obj.put("alamat", broker.getAlamat());
		obj.put("saldoUang", String.valueOf(broker.getSaldoUang()));
		obj.put("saldoSaham", String.valueOf(broker.getSaldoSaham()));
		String data="";
		try {
			data = readURL("http://localhost:8080/sigma/core/broker/create/json/"+obj.toJSONString());
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		JSONParser parser = new JSONParser();
		JSONObject jObject;
		String json = null ;
		try {
			jObject = (JSONObject) parser.parse(data);
			json= (String)jObject.get("status");
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		System.out.println(json);
		if (json.equals("sukses insert")) {
			return new ModelAndView("redirect:/");
		}else{
			return new ModelAndView("redirect:/formInsertNew");
		}

		
	}

	@RequestMapping(value = "/deleteBroker/id/{id}", method = RequestMethod.GET)
	public String deleteBroker(@PathVariable("id") String id) {

		String data="";
		try {
			data = readURL("http://localhost:8080/sigma/core/broker/delete/id/"+id);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		JSONParser parser = new JSONParser();
		JSONObject jObject;
		String json = null ;
		try {
			jObject = (JSONObject) parser.parse(data);
			json= (String)jObject.get("status");
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		System.out.println(json);
		if (json.equals("sukses update")) {
			return "redirect:/";
		}else{
			return "redirect:/";
		}
	}

	// action untuk form update broker
	@RequestMapping(value = "/updateBroker", method = RequestMethod.POST)
	public ModelAndView updateBrooker(@ModelAttribute("Broker") Broker broker) {
		JSONObject obj = new JSONObject();
		obj.put("idBroker", broker.getIdBroker());
		obj.put("nama", broker.getNamaBroker());
		obj.put("alamat", broker.getAlamat());
		obj.put("saldoUang", String.valueOf(broker.getSaldoUang()));
		obj.put("saldoSaham", String.valueOf(broker.getSaldoSaham()));
		System.out.println(String.valueOf(broker.getSaldoUang()));
		String data="";
		try {
			data = readURL("http://localhost:8080/sigma/core/broker/update/json/"+obj.toJSONString());
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		JSONParser parser = new JSONParser();
		JSONObject jObject;
		String json = null ;
		try {
			jObject = (JSONObject) parser.parse(data);
			json= (String)jObject.get("status");
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		System.out.println(json);
		if (json.equals("sukses update")) {
			return new ModelAndView("redirect:/formUpdateBroker/id/"+broker.getIdBroker());
		}else{
			return new ModelAndView("redirect:/");
		}
	}

	public String readURL(String url) throws IOException {
		URL yahoo = new URL(url);
		URLConnection yc = yahoo.openConnection();
		BufferedReader in = new BufferedReader(new InputStreamReader(
				yc.getInputStream()));
		String inputLine;
		String tampung = "";
		while ((inputLine = in.readLine()) != null) {
			tampung += inputLine;
			System.out.println(inputLine);
		}
		in.close();

		return tampung;
	}
}
